package game.serverenv;

import game.constants.GameConstant;
import game.entity.Hero;
import game.module.hero.dao.HeroDao;
import game.module.itemnew.beans.ItemStorage;
import game.module.itemnew.beans.ItemStorage.Item;
import game.module.itemnew.dao.ItemDao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Queue;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.Cache.ValueWrapper;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;

@Component
public class DataPersistenceManager {

	@Autowired
	private GameServerOnlineManager gameServerOnlineManager;

	@Autowired
	private HeroDao heroDao;

	@Autowired
	private ItemDao itemDao;

	@Autowired
	public CacheManager cacheManager;

	public void persistence() {
		saveCharacters();
		saveItems();
	}

	@SuppressWarnings("unchecked")
	public void saveItems() {
		Cache cache = cacheManager.getCache(GameConstant.CACHE_GOODS);
		List<Integer> heroIdList = heroDao.getRoleIdList();
		List<ItemStorage> itemStorages = new ArrayList<ItemStorage>();
		List<Integer> validHeroIdList = new ArrayList<Integer>();
		for (Integer heroId : heroIdList) {
			ValueWrapper cacheBodyItems = cache.get(GameConstant.CACHE_GOODS_BODY + heroId);
			ValueWrapper cacheBagItems =  cache.get(GameConstant.CACHE_GOODS_BAG + heroId);
			if (cacheBodyItems != null) {
				ItemStorage itemStorage = new ItemStorage();
				List<ItemStorage.Item> itemList = new ArrayList<ItemStorage.Item>();
				itemList.addAll(((Map<Short, Item>)cacheBodyItems.get()).values());
				itemList.addAll(((Map<Short, Item>)cacheBagItems.get()).values());
				itemStorage.setItemList(itemList);
				itemStorages.add(itemStorage);
				validHeroIdList.add(heroId);
			}
		}
		itemDao.batchUpdateItem(itemStorages, validHeroIdList);
	}

	public void saveCharacters() {
		Queue<Hero> heros = gameServerOnlineManager.getCharacterList();
		heroDao.batchUpdateHero(heros);
	}

}
